package gui;

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;

public class View extends JFrame{
	
	JPanel panel = new JPanel();
	
	public View(){
		viewList();
	}
	
	public void viewList(){
		setSize(600,400);
		setLocation(500,280);
		setResizable(false);
		panel.setLayout(null);
		
		File[] files = getList();
		panel.setAutoscrolls(true);
		
		int  y = 0;
		for(final File f: files){
			try {
				Scanner scanFile = new Scanner(f);
				JButton btask = new JButton(scanFile.nextLine());
				btask.setBounds(0, y, 600, 40);
				y += 40;
				panel.add(btask);
				btask.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent ae) {
						Task task = new Task(f);
						task.setVisible(true);
					}		
				});
				scanFile.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
		panel.setPreferredSize(new Dimension(600,y));
		JScrollPane scroll = new JScrollPane (panel, 
				   JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		getContentPane().add(scroll);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setVisible(true);
	}
	
	public File[] getList(){
		File dir = new File(Login.data_dir);
		
		File[] files = dir.listFiles(new FilenameFilter() {
		    public boolean accept(File dir, String name) {
		        return name.toLowerCase().endsWith(".txt") && name.toLowerCase().startsWith(Login.user+"-");
		    }
		});

		return files;
	}
}
